//
//  SceneSetting.m
//  GKBHouse
//
//  Created by  on 12-7-24.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "SceneSetting.h"
#import "GKBNavigationBar.h"
#import "GKBMainController.h"
#import "SceneSetCell.h"
#import "Global1.h"
@implementation SceneSetting
@synthesize equipments;
@synthesize sceneID;
@synthesize sceneName;
@synthesize OpenEqus;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self.view setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"background.png"]]];
    [self initTopBar];
    [self initLabel];
    
  //  
    [table setBackgroundColor:[UIColor redColor]];
    [table setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"sceneTableBack.png"]]];
    [[table layer]setCornerRadius:9];
    [[table layer]setMasksToBounds:YES];
    
    GKBMainController *main = [GKBMainController mainCtr];
    self.equipments = main.equipments;
    [okButton addTarget:self action:@selector(okAction) forControlEvents:UIControlEventTouchUpInside];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

//- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
//{
//    // Return YES for supported orientations
//    return (interfaceOrientation == UIInterfaceOrientationLandscapeRight);
//}

- (void)initTopBar
{    
    GKBNavigationBar *topBar = [[GKBNavigationBar alloc]init];
    [topBar setTarget:self returnAction:@selector(dismissView) withTitle:NSLocalizedString(@"sceneSetting", nil)];
    [self.view addSubview:topBar];    
    [topBar release];
    
}
- (void)dismissView
{
    [self dismissModalViewControllerAnimated:NO];
}
- (void)initLabel
{
    [nameLabel setText:NSLocalizedString(@"sceneName", nil)];
    [okButton setTitle:NSLocalizedString(@"ok", nil) forState:UIControlStateNormal];
   
    [nameText setText:self.sceneName];
    nameText.delegate = self;
    
  //  [nameText addTarget:self action: @selector(changePhoneNumValue) forControlEvents:UIControlEventEditingChanged];//手机号码
}

-(void)changePhoneNumValue
{
    int MaxLen = 4;
    NSString* szText = [nameText text];
    if ([szText length]> MaxLen) 
    {
        nameText.text = [szText substringToIndex:MaxLen];
    }
}

#pragma mark - UITextFielDelegate

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
//    NSLog(@"input:%@",[UITextInputMode currentInputMode].primaryLanguage);
//     
////    NSUInteger newLength = [textField.text length]+[string length] - range.length;
////    return (newLength > 5) ? NO:YES;
//    NSLog(@"%@, %d, %d, %@", textField.text, range.length, range.location, string);
//    if ([string length]>0) {
//        unichar c = [string characterAtIndex:0];   
//        int index = c - HANZI_START;
//        if (index >= 0 && index <= HANZI_COUNT){
//            NSLog(@"汉字");
//        }
//        else
//        {
//            NSLog(@"英文");
//        }
//    }
//
   return YES;

}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    int MaxLen = 4;
    NSString* szText = [nameText text];
    if ([szText length]> MaxLen) 
    {
        nameText.text = [szText substringToIndex:MaxLen];
    }
    [textField resignFirstResponder];
    return YES;
}


#pragma mark - UITableVIewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}

#pragma mark - UITableViewDataSourceDelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [self.equipments count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifyCell = @"sceneSetCell";
    SceneSetCell *cell = (SceneSetCell*)[tableView dequeueReusableCellWithIdentifier:identifyCell];
    if (cell == nil) {
        cell = [[[SceneSetCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifyCell]autorelease];
    }
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    NSDictionary *equ = [self.equipments objectAtIndex:indexPath.row];
    
    NSString *name = [equ objectForKey:@"name"];
    NSString *switchId = [equ objectForKey:@"switchId"];
    
    [cell.check setTag:indexPath.row];
    [cell.check addTarget:self action:@selector(checkAction:) forControlEvents:UIControlEventTouchUpInside];
    
    if ([self.OpenEqus containsObject:switchId]) {
        [cell.check setSelected:YES];
    }
    else
    {
        [cell.check setSelected:NO];
    }
    [cell.name setText:name];
    return cell;
}
- (void)checkAction:(UIButton *)but
{
    but.selected = !but.selected;
    NSDictionary *equ = [self.equipments objectAtIndex:but.tag];
    NSString *switchId = [equ objectForKey:@"switchId"];

    if (but.selected) {
        [self.OpenEqus addObject:switchId];
    }
    else
    {
        [self.OpenEqus removeObject:switchId];
    }
}
- (void)okAction
{
    NSString *sceneFile = [AppFile sceneFile];
    if (!sceneFile) {
        return;
    }
    NSMutableDictionary *allScene = [NSMutableDictionary dictionaryWithContentsOfFile:sceneFile];
    if (allScene == nil) {
        allScene = [NSMutableDictionary dictionary];
    }
   // self.sceneID;
    NSMutableDictionary *scene = [allScene objectForKey:self.sceneID];
    if (scene == nil) {
        scene = [NSMutableDictionary dictionary];
    }
    [scene setObject:nameText.text forKey:@"name"];
    [scene setObject:self.OpenEqus forKey:@"OpenEqus"];
    [allScene setObject:scene forKey:self.sceneID];
    BOOL save = [allScene writeToFile:sceneFile atomically:YES];
    if (save) {        
        NSString *sceneId = self.sceneID;
        GKBMainController *main = [GKBMainController mainCtr];
        BOOL find = NO;
        for (NewEquipment *equ in main.sceneArray) {
            NSInteger equSceneID = [equ.switchId integerValue];
            if ([sceneId integerValue] == equSceneID) {
                [equ setName:nameText.text];
                [equ setOpenEques:self.OpenEqus];
                find = YES;
                break;
            }
            
        }
        if (!find) {
            NewEquipment *equipment = [[NewEquipment alloc]init];
            
            [equipment setName:nameText.text];
            NSString *type = [NSString stringWithFormat:@"%d", DeviceTypeScene];
            [equipment setType:type];
            [equipment setSwitchId:sceneId];
            [equipment setRegulate:@"3"];
            [equipment setState:kStateOFF];
            [equipment setOpenEques:self.OpenEqus];
            NSLog(@"%@", main.sceneArray);
            [main.sceneArray addObject:equipment];
            NSLog(@"%@", main.sceneArray);
            [equipment release];
        }
        
        [self dismissView];
        [main initScene];
        [GKBMainController refreshDevices];
    }
        
}
@end
